"use client"

import React, { useEffect, useState } from "react";
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button";
import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from "@/components/ui/form";
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import axios from 'axios'
import { downloadCsvFile, getSentenceScore, getSentencesScoreAndId } from "@/utils";
import { useRequest } from 'ahooks'
import * as echarts from 'echarts';
import PieGraph from "@/components/echarts/pie";
import { DataTableDemo } from "@/components/DataTable";


interface IProps {
  name?: string
}

const formSchema = z.object({
  sentence: z.string().min(1).max(100),
})

const fileUploadSchema = z.object({
  file: z.instanceof(FileList).refine((file) => file?.length == 1, 'File is required.')
})



const ClassificationPage: React.FC<IProps> = (props) => {
  

  const [singleSentenceScore, setSingleSentenceScore] = useState<number[]>([]);
  const [download, setDownload] = useState(false);


  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      sentence: "",
    },
  })

  const fileUploadForm = useForm<z.infer<typeof fileUploadSchema>>({
    resolver: zodResolver(fileUploadSchema),
  });

  const fileRef = fileUploadForm.register("file");

  async function onSubmit(values: z.infer<typeof formSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    console.log(values);
    // const info = await getSentenceScore(values.sentence);
    // console.log('查看收到的信息', info);
    runSentenceScore(values.sentence);


  }

  async function fileUploadSubmit(values: z.infer<typeof fileUploadSchema>) {
    const form = new FormData();
    
    form.append('filename', values.file[0]);
    // const info = await axios.post('http://127.0.0.1:5000/test/csv/score', form)
    // console.log('查看info', info);
    
    runSentencesScore(form);
  }


  const { loading: isSentencesScore, run: runSentencesScore } = useRequest((formData): any => { 
    return getSentencesScoreAndId(formData)
   }, {
    manual: true,
    onSuccess: (res: string) => { 
      console.log('查看返回的长string', res);
      setDownload(true);
     }
   })

  const { loading: isSentenceScoreLoading, run: runSentenceScore } = useRequest((sentence: string): any => {
    return getSentenceScore(sentence)
  }, {
    manual: true,
    debounceWait: 300,
    onSuccess: (res: string) => {
      console.log('查看成功的输出：', res, typeof res);
      let result = res.slice(1, res.length - 1).split(', ');
      let scoreArr = result.map((i) => {
        return Number(i)
      })
      console.log('查看修改后的数据', scoreArr);
      setSingleSentenceScore(scoreArr);

    }
  })

  return (
    <div >
      <div className="mt-5">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={form.control}
              name="sentence"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>请输入英文语句：</FormLabel>
                  <FormControl>
                    <Input placeholder="Sentence..." {...field} />
                  </FormControl>
                  <FormDescription>
                    This is your public display name.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit" disabled={isSentenceScoreLoading} >提交</Button>
          </form>
        </Form>
        <div>

        </div>
      </div>
      <div>
        {
          singleSentenceScore.length == 0 ? null : (isSentenceScoreLoading ? null :
            <div>
              <PieGraph data={singleSentenceScore} graphType="pie" container="pcscharge" title="分析结果" />
            </div>
          )}
      </div>

      <div className="mt-20">
        <Form {...fileUploadForm}>
          <form onSubmit={fileUploadForm.handleSubmit(fileUploadSubmit)} className="space-y-8">
            <FormField
              control={fileUploadForm.control}
              name="file"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>请上传csv文件：</FormLabel>
                  <FormControl>
                  <Input type="file" placeholder="shadcn" {...fileRef} />
                  </FormControl>
                  <FormDescription>
                    This is your public display name.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit" disabled={isSentencesScore}>提交</Button>
          </form>
        </Form>
      </div>
      {/* <DataTableDemo /> */}
      {download ? <a href="http://127.0.0.1:5000/test/download" className="bg-zinc-900 inline-block w-36 leading-10 text-gray-100 text-center rounded-xl hover:bg-zinc-800 transition-all duration-200 mt-10"  >下载源文件</a> : null}
      
    </div>
  )
}

export default ClassificationPage;